package top.shaozuo.simple.gitee.oauth.web;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import top.shaozuo.simple.gitee.oauth.config.OauthProperties;
import top.shaozuo.simple.gitee.oauth.dto.AccessDto;
import top.shaozuo.simple.gitee.oauth.dto.UserDto;

@Controller
@RequestMapping("gitee")
public class GiteeController {

	@Autowired
	private OauthProperties oauthProperties;

	private Gson gson = new Gson();

	@RequestMapping("")
	public String index(Model model) {
		HttpUrl url = HttpUrl.parse("https://gitee.com/oauth/authorize").newBuilder()
		        .addQueryParameter("client_id", oauthProperties.getClientId())
		        .addQueryParameter("redirect_uri", oauthProperties.getCallback())
		        .addQueryParameter("response_type", "code").build();
		model.addAttribute("authUrl", url.toString());
		return "gitee/index";
	}

	/**
	 * 得到code 并获取 accessToken
	 * 
	 * @param code
	 * @param state
	 * @return
	 */
	@RequestMapping(value = { "redirectUri", "callback", "redirect" })
	public String redirect(Model model, String code, String state) {
		System.out.println("code : " + code);
		System.out.println("state : " + state);
		AccessDto acc = requestAccessToken(code);
		if (acc != null) {
			UserDto userInfo = requestUserInfo(acc.getAccessToken());
			model.addAttribute("userInfo", userInfo);
		} else {
			model.addAttribute("userInfo", new UserDto());
			model.addAttribute("errors", "获取AccessToken失败");
		}
		return "gitee/info";
	}

	private AccessDto requestAccessToken(String code) {
		OkHttpClient client = new OkHttpClient();

		HttpUrl.Builder httpBuilder = HttpUrl.parse("https://gitee.com/oauth/token").newBuilder();
		httpBuilder.addQueryParameter("grant_type", "authorization_code");
		httpBuilder.addQueryParameter("code", code);
		httpBuilder.addQueryParameter("client_id", oauthProperties.getClientId());
		httpBuilder.addQueryParameter("redirect_uri", oauthProperties.getCallback());
		FormBody formBody = new FormBody.Builder()
		        .add("client_secret", oauthProperties.getClientSecret()).build();
		System.out.println(httpBuilder.build());
		Request request = new Request.Builder().url(httpBuilder.build()).post(formBody).build();

		try (Response response = client.newCall(request).execute()) {
			String responseStr = response.body().string();
			System.out.println(responseStr);
			return gson.fromJson(responseStr, AccessDto.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private UserDto requestUserInfo(String accessToken) {
		OkHttpClient client = new OkHttpClient();

		HttpUrl.Builder httpBuilder = HttpUrl.parse("https://gitee.com/api/v5/user").newBuilder();
		httpBuilder.addQueryParameter("access_token", accessToken);
		Request request = new Request.Builder().url(httpBuilder.build()).get().build();

		try (Response response = client.newCall(request).execute()) {
			return gson.fromJson(response.body().string(), UserDto.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
